package com.vanky.graph.service.impl;

import com.vanky.graph.pojo.Edge;
import com.vanky.graph.properties.HugeClientProperties;
import com.vanky.graph.service.EdgeService;
import com.vanky.graph.utils.JsonUtil;
import groovy.util.logging.Slf4j;
import org.apache.hugegraph.driver.GremlinManager;
import org.apache.hugegraph.driver.HugeClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@Slf4j
@ComponentScan("com")
public class EdgeServiceImpl implements EdgeService {

    @Autowired
    private HugeClientProperties hugeClientProperties;

    /*
     * 查询所有边关系
     */
    @Override
    public List<Edge> getAllEdge(){

        //连接到 HugeGraph 数据库
        HugeClient hugeClient = HugeClient.builder(hugeClientProperties.getUrl(),hugeClientProperties.getGraph())
                .build();

        //获取 gremlin 管理器
        GremlinManager gremlin = hugeClient.gremlin();

        //执行gremlin语句进行查询
        List<Object> data = gremlin.gremlin("g.V().as('vertex')\n" +
                "  .bothE().as('edge').dedup()\n" +
                "  .bothV().as('connectedVertex')\n" +
                "  .where('vertex', not(eq('connectedVertex')))\n" +
                "  .select('vertex','edge','connectedVertex')\n" +
                "  .by(valueMap())\n" +
                "  .by(valueMap(true))\n" +
                "  .by(valueMap())").execute().data();

        //关闭服务器连接
        hugeClient.close();

        //返回json格式的结果
        return JsonUtil.toJson(data, Edge.class);
    }
}
